package hrms.controller;

import hrms.entity.*;
import hrms.service.AccountService;
import hrms.service.CandidateService;
import hrms.service.RecruitmentService;
import hrms.service.StaffService;
import hrms.util.JWTUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/candidate")
public class CandidateController {

    @Autowired
    private CandidateService candidateService;

    @Autowired
    private AccountService accountService;

    @Autowired
    private StaffService staffService;

    public Staff getStaff(HttpServletRequest request){
        String token = request.getHeader("token");
        String id = JWTUtil.getId(token);
        Integer staffId = accountService.findStaffIdById(Integer.valueOf(id));
        return staffService.findById(staffId);
    }

    @GetMapping("/find")
    public Result findById(Integer id){
        Candidate candidate = candidateService.findById(id);
        if(candidate == null){
            return Result.fail().error("该ID不存在！");
        }
        Map<String, Object> map = new HashMap<>();
        map.put("candidate", candidate);
        return Result.success().addMap(map);
    }

    @PostMapping("/insertCandidate")
    public Result insertCandidate(@RequestBody Candidate candidate){
        candidateService.insertCandidate(candidate);
        return Result.success();
    }

    @GetMapping("/findStatus0")
    public Result findAll(){
        List<Candidate> all = candidateService.findAll();
        Map<String, Object> map = new HashMap<>();
        map.put("candidates", all);
        return Result.success().addMap(map);
    }

    @PostMapping("/updateRecord")
    public Result updateRecord(@RequestBody Candidate candidate){
        candidateService.updateRecord(candidate);
        return Result.success();
    }

    @PostMapping("/updateStatus")
    public Result updateStatus(@RequestBody Candidate candidate){
        // 更新应聘者状态
        candidateService.updateStatus(candidate);
        // 将应聘者candidate加入员工staff
        Staff staff = new Staff();
        staff.setName(candidate.getName());
        staff.setGender(candidate.getGender());
        staff.setPhone(candidate.getPhone());
        staff.setEmail(candidate.getEmail());
        Department department = candidate.getRecruitment().getDepartment();
        staff.setDepartment(department);
        Post post = candidate.getRecruitment().getPost();
        staff.setPost(post);
        staff.setBirthday(candidate.getBirthday());
        staff.setEducation(candidate.getEducation());
        staffService.insertStaff(staff);
        // 删除该应聘者candidate在其他招聘表recruitment的投递
        candidateService.updateStatusByPhone(candidate.getPhone());
        return Result.success();
    }

}
